package service;

import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pojo.User;
import utils.SqlSessionFactoryUtils;

public class UserService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /*** 登录方法 */
    public User login(String username, String password) {
        //1. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //2. 获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //3. 调用方法
        User user = mapper.selectByUsername(username);
        //4. 验证密码
        if (user != null) {
            if (password.equals(user.getPassword())) {
                //密码不符
                return user;
            } else {
                //验证通过
                return null;
            }
        }
        return null;
    }
//    注册用户
    public boolean register(String username,String password){
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//        1.先检查能否被注册
        User user = userMapper.selectByUsername(username);
        if (user!=null){
//            如果此条件成立，代表数据库中已有该名称的用户
            return false;
        }
//      2.如果能被注册，则执行注册操作
        User newUser = new User(null, username, password);
        int i = userMapper.add(newUser);
        sqlSession.commit();
        sqlSession.close();
        return i == 1;
    }
//    检查用户名是否存在
//    true存在 false不存在
    public boolean checkUsername(String username){
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//        1.先检查能否被注册
        User user = userMapper.selectByUsername(username);
        if (user!=null){
//            如果此条件成立，代表数据库中已有该名称的用户
            return true;
        }
        sqlSession.close();
        return  false;
    }

    public boolean add(String username, String password) {
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.selectByUsername(username);
        if (user!=null) {
            return false;
        }
            User newUser = new User(null,username,password);
            int i = userMapper.add(newUser);
            sqlSession.commit();
            sqlSession.close();
            return i>0;
    }
}
